import {NextResponse} from 'next/server';
import fs from 'fs';
import path from 'path';
import ffmpeg from 'fluent-ffmpeg';
import {exec} from 'node:child_process';

ffmpeg.setFfmpegPath('/opt/homebrew/bin/ffmpeg');

export async function POST(request: Request) {
    try {
        const {videoPath, fps, zoom, outputDir, width, height, outputType} = await request.json();

        if (!videoPath) {
            return NextResponse.json({error: 'Video path is required'}, {status: 400});
        }

        // const videoDir = path.dirname(videoPath);
        // const videoName = path.basename(videoPath, path.extname(videoPath));
        // const outputDir = path.join(videoDir, `${videoName}_output`);

        // 创建输出目录
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, {recursive: true});
        }

        // 生成截图命令
        let command = '';

        if (outputType === 'zoom') {
            command = `ffmpeg -i "${videoPath}" -vf "select=not(mod(n\\,${fps})),scale=iw*${zoom}:ih*${zoom}" -fps_mode vfr -q:v 1 "${outputDir}/%04d.jpg"`;
        } else if (outputType === 'width') {
            command = `ffmpeg -i "${videoPath}" -vf "select=not(mod(n\\,${fps})),scale=${width}:${height}" -fps_mode vfr -q:v 1 "${outputDir}/%04d.jpg"`;
        }

        exec(command, (error, stdout, stderr) => {
            if (error) {
                console.error(`执行错误: ${error.message}`);
                return;
            }
            if (stderr) {
                console.error(`stderr: ${stderr}`);
            }
            console.log(`stdout: ${stdout}`);
            console.log('截图生成成功');
        });

        return NextResponse.json({message: 'Video processing started', outputDir});
    } catch (error) {
        console.error('Error:', error);
        return NextResponse.json({error: 'Internal server error'}, {status: 500});
    }
}
